﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Xml;

namespace LsUpdater.API
{
   public  class AutoCheckUpdate
    {
       Thread thread = null;
       public AutoCheckUpdate()
       {
           thread = new Thread(new ThreadStart(AutoCheckUpdate1));
           thread.Start();
       }
       #region 自动检测更新程序
       private void AutoCheckUpdate1()
       {
           Comm.listc.Clear();
           Comm.listClearList.Clear();
           if (!File.Exists(Application.StartupPath + "\\update.xml"))
           {
               //如果本地没有update.xml文件,则生成一个.
               #region 生成update.xml
               //生成update.xml
               StringBuilder str = new StringBuilder();
               str.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n");
               str.Append("<updater>\r\n");
               str.Append("<info>\r\n");
               str.Append("<appname>dodiv编辑器</appname>\r\n");
               str.Append("<processname>dodiv编辑器</processname>\r\n");
               str.Append("<xmlurl>http://www.zhanzhebian.com/soft/update\\update.xml</xmlurl>\r\n");
               str.Append("<remotedir>http://www.zhanzhebian.com/soft/update/</remotedir>");
               str.Append("<version>1.0.0.1</version>\r\n");
               str.Append("<datetime>2011-2-16</datetime>\r\n");
               str.Append("<isMustUpdate>0</isMustUpdate>\r\n");
               str.Append("<desc><![CDATA[]]></desc>");

               DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);
               foreach (FileInfo item in dir.GetFiles())
               {
                   if (item.Extension != ".xml")
                   {
                       FileVersionInfo myFileVersion = FileVersionInfo.GetVersionInfo(item.FullName);
                       String strFileVersion = string.Format("{0}.{1}.{2}.{3}", myFileVersion.FileMajorPart, myFileVersion.FileMinorPart, myFileVersion.FileBuildPart, myFileVersion.FilePrivatePart);
                       //string strFileVersion = myFileVersion.FileVersion;
                       str.Append("<file>\r\n");
                       str.Append("<path>" + item.Name + "</path>\r\n");
                       str.Append("<version>" + strFileVersion + "</version>\r\n");
                       str.Append("</file>\r\n");
                   }
               }
               str.Append("</updater>");
               FileHelper.WriteFile(Application.StartupPath + "\\update.xml", str.ToString(), "utf-8");
               #endregion
           }

           UpdateInfo infoLocal = XmlToList(Application.StartupPath + "\\update.xml");
           Comm.infoRemote = XmlToList(infoLocal.xmlurl);

           if (Comm.infoRemote.version != infoLocal.version)
           {
               //强制升级
               if (Comm.infoRemote.isMustUpdate)
               {
                   UpdateStart(infoLocal);
               }
               else
               {
                   if (MessageBox.Show("发现有新的版本更新,是否升级?", "升级提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                   {
                       UpdateStart(infoLocal);
                   }
                   else
                   {
                       Environment.Exit(0);
                       return;
                   }
               }
           }
           else
           {
               Environment.Exit(0);
               return;
           }

       }

       private void UpdateStart(UpdateInfo infoLocal)
       {
           List<UpdateFile> listRemote = Comm.infoRemote.UpdateFiles;
           List<UpdateFile> listLocal = infoLocal.UpdateFiles;

           foreach (var remoteitem in listRemote)
           {
               //如果本地有和远程相同的文件,版本号不同,更新它
               if (listLocal.Exists(item => item.path == remoteitem.path && item.version != remoteitem.version))
               {
                   Comm.listc.Add(remoteitem);
               }
               else if (!listLocal.Exists(item => item.path == remoteitem.path))//如果不存在.下载更新到本地
               {
                   Comm.listc.Add(remoteitem);
               }
           }

           #region 遍历需要删除的文件
           //遍历需要删除的文件
           foreach (var localitem in listLocal)
           {
               if (!listRemote.Exists(item => item.path == localitem.path) && localitem.path.ToLower().Contains(".dll"))
               {
                   Comm.listClearList.Add(localitem);
               }
           }
           #endregion

           Application.Run(new UpdaterFrm());
           thread = null;
       }
       #endregion

       private UpdateInfo XmlToList(string xmlfile)
       {
           UpdateInfo info = new UpdateInfo();
           try
           {
               XmlNode node = XMLHelper.GetXmlNodeByXpath(xmlfile, "updater/info");
               info.appname = node.SelectSingleNode("appname").InnerText;
               info.ProcessName = node.SelectSingleNode("processname").InnerText;
               info.xmlurl = node.SelectSingleNode("xmlurl").InnerText;
               info.version = node.SelectSingleNode("version").InnerText;
               info.RemoteDir = node.SelectSingleNode("remotedir").InnerText;
               info.datetime = node.SelectSingleNode("datetime").InnerText;
               info.isMustUpdate = node.SelectSingleNode("isMustUpdate").InnerText == "0" ? false : true;
               info.desc = node.SelectSingleNode("desc").InnerText;
               List<UpdateFile> listf = new List<UpdateFile>();
               XmlNodeList nodelist = XMLHelper.GetXmlNodeListByXpath(xmlfile, "updater/files/file");
               foreach (XmlNode item in nodelist)
               {
                   UpdateFile file = new UpdateFile();
                   file.path = item.SelectSingleNode("path").InnerText;
                   file.version = item.SelectSingleNode("version").InnerText;
                   listf.Add(file);
               }
               info.UpdateFiles = listf;
           }
           catch (Exception ex)
           {
               //MessageBox.Show("获取远程更新文件失败!");
               //MessageBox.Show(ex.Message);
               Environment.Exit(0);
               return null;
           }
           return info;
       }
    }
}
